//公告管理
import {
  Input,
  Select,
  Button,
  Table,
  Space,
  Radio,
  Modal,
  DatePicker,
  message,
  Form,

} from "antd";
import { useEffect, useState } from "react";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import "../../componet/SystemManeger/Advertisement.css";
import axios from "../../utils/myAixos";
const { TextArea } = Input;
const Announcement = () => {
  //删除的数据
  const [delDates, setDelDates] = useState({});
  //删除的模态框
  const [messageApi, contextHolder] = message.useMessage();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isselectModalOpen, setisselectModalOpen] = useState(false);
  const [issendModalOpen, setissendModalOpen] = useState(false);
    //用于删除前端传递数据
   const [delArrId,setDelArrId]=useState([])
   //用于传输后端的数据
   const [ArrId,setArrId]=useState("")
  const handleOk = () => {
    console.log(delArrId)
    console.log(ArrId)
    // let arrDate={
    //   u_id:delArrId,
    // }
    let arr=[...dataList]
  for(let i=0;i<=arr.length-1;i++){
    if(arr[i].n_id===delArrId){
      arr.splice(i,1)
    }
  }
    setDateList(arr)
    setIsModalOpen(false);
    axios({
      url: "/noticeDel",
      method: "post",
      data: {
        idArr: ArrId,
      },
    })
      .then((res) => {
        console.log("获取所有学生数据", res);

        if (res.status === 200) {
         console.log("数据删除成功")
         messageApi.info("删除成功!");
        }
      })
      .catch((err) => {
        console.log("获取所有学生数据1111", err);
      });
    // console.log(11)
    // setDateList(data);
    // console.log(data)

  
    // setIsSuccessModalOpen(true);
    console.log(delDates);
  };
  message.config({
    top: 500,
    duration: 2,
    maxCount: 3,
    rtl: true,
    prefixCls: "my-message",
  });
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const handleselectCancel = () => {
    setisselectModalOpen(false);
  };
  const handleselectOk = () => {
    setisselectModalOpen(false);
    // setIsSuccessModalOpen(true);
    console.log(delDates);
  };
  const handlesendCancel = () => {
    setissendModalOpen(false)
  };
  const handlesendOk = () => {
    setisselectModalOpen(false);
    // setIsSuccessModalOpen(true);
    setissendModalOpen(false)
  };
  //上方输入框和下拉框
  const [inputValue, setInputValue] = useState("");
  const [swiper, setSwiper] = useState("");
  const [times, setTimes] = useState("");
  const swiperChange = (value) => {
    setSwiper(value);
  };

  const onChange = (date, dateString) => {
    console.log(date, dateString);
    setTimes(dateString);
  };
  const changeInput = (value) => {
    setInputValue(value.target.value);
  };
  //获取所有信息
  const getALLDate=()=>{
    axios({
      url: "/getNoticeData",
      method: "post",
    })
      .then((res) => {
        console.log("获取所有学生数据", res);

        if (res.status === 200) {
          setDateList(res.data.data);
          setdatas(res.data.data)
          // console.log(res.data.data.length)
          let num = Math.floor(res.data.data.length / 5);
          let yushu = res.data.data.length % 5;
          // console.log(num,yushu)
          setPageNmu(num);
          setPageYu(yushu);
        }
      })
      .catch((err) => {
        console.log("获取所有学生数据1111", err);
      });
  }
  const searchDate = () => {
    console.log(swiper);
    console.log(times);
    let time=times
  
    console.log(inputValue);
    let arr={
      title: inputValue,
      time:times,
      people:swiper,
    }
    axios({
      url: "/noticeSearch",
      method: "post",
      data: arr,
    })
      .then((res) => {
        // console.log(res);
        if (res.status === 200) {
          console.log(res.data.data)
          setDateList(res.data.data)
        } else {
         
        }
      })
      .catch((err) => {
        console.log(err);
       
      });
  };
  //查看表格的函数
  const [selectDate,setSelectDate]=useState({})
  const changeDate = (record) => {
    console.log(record+"---------------");
    console.log(record);
  
    setisselectModalOpen(true)
    setSelectDate(record)
  };
  const delDate = (record) => {
    setDelArrId(record.n_id)
   
    // console.log(record);
    if(selectedRowKeys.length===0){
      messageApi.info("没有选择删除的数据!");
     }else{
      setIsModalOpen(true);
     }
      
    setDelDates(record);
    
  };

  //表格///
  const [dataList, setDateList] = useState([]);
  const data = [
    {
      id: 0,
      name: "夏季大促销1",
      people: "安和桥南",
      time: "2021-3-20",
      content:"dasv svdsefedsvbdsgsvsdvdbdfgbb",
    },
    {
      id: 1,
      name: "夏季大促销",
      people: "安和桥南",
      time: "2021-3-20",
      content:"dasv svdsefedsvbdsgsvsdvdbdfgbb",
    },
    {
      id: 2,
      name: "夏季大促销",
      people: "安和桥南",
      time: "2021-3-20",
      content:"dasv svdsefedsvbdsgsvsdvdbdfgbb",
    },
    {
      id: 3,
      name: "夏季大促销",
      people: "安和桥南",
      time: "2021-3-20",
      content:"dasv svdsefedsvbdsgsvsdvdbdfgbb",
    },
    {
      id: 4,
      name: "夏季大促销",
      people: "安和桥南",
      time: "2021-3-20",
    },
    {
      id: 5,
      name: "夏季大促销",
      people: "安和桥南",
      time: "2021-3-20",
      content:"dasv svdsefedsvbdsgsvsdvdbdfgbb",
    },
    {
      id: 6,
      name: "夏季大促销",
      people: "安和桥南",
      time: "2021-3-20",
      content:"dasv svdsefedsvbdsgsvsdvdbdfgbb",
    },
    {
      id: 7,
      name: "夏季大促销",
      people: "安和桥南",
      time: "2021-3-20",
      content:"dasv svdsefedsvbdsgsvsdvdbdfgbb",
    },
    {
      id: 8,
      name: "夏季大促销",
      people: "安和桥南",
      time: "2021-3-20",
      content:"dasv svdsefedsvbdsgsvsdvdbdfgbb",
    },
    {
      id: 9,
      name: "夏季大促销",
      people: "安和桥南",
      time: "2021-3-20",
      content:"dasv svdsefedsvbdsgsvsdvdbdfgbb",
    },
    {
      id: 10,
      name: "夏季大促销",
      people: "安和桥南",
      time: "2021-3-20",
      content:"dasv svdsefedsvbdsgsvsdvdbdfgbb",
    },
    {
      id: 11,
      name: "夏季大促销",
      people: "安和桥南",
      time: "2021-3-20",
      content:"dasv svdsefedsvbdsgsvsdvdbdfgbb",
    },
  ];
  const columns = [
    {
      title: "编号",
      dataIndex: "n_id",
      key: "n_id",
      width: 80,
    },
    {
      title: "消息标题",
      dataIndex: "n_title",
      key: "n_title",
      width: 120,
    },
    {
      title: "发布时间",
      dataIndex: "n_time",
      key: "n_time",
      width: 120,
    },
    {
      title: "发布人员",
      dataIndex: "n_user",
      key: "n_user",
      width: 120,
    },

    {
      title: "操作",
      key: "num",
      render: (_, record) => (
        <Space size="middle">
          <button
            type=""
            onClick={() => {
              changeDate(record);
            }}
            style={{
              width: "50px",
              backgroundColor: "white",
              border: "0px",
              color: "#00d1ff",
            }}
          >
            查看
          </button>
          <button
            type=""
            onClick={() => {
              delDate(record);
            }}
            style={{
              width: "50px",
              backgroundColor: "white",
              border: "0px",
              color: "#00d1ff",
            }}
          >
            删除
          </button>
        </Space>
      ),
      width: 60,
    },
  ];
  //   setDateList();
  //多少页
  const [pageNmu, setPageNmu] = useState("");
  //页的余数
  const [pageYU, setPageYu] = useState("");
  const[datas,setdatas]=useState([])
  useEffect(() => {
    axios({
      url: "/getNoticeData",
      method: "post",
    })
      .then((res) => {
        console.log("获取所有学生数据", res);

        if (res.status === 200) {
          setDateList(res.data.data);
          setdatas(res.data.data)
          // console.log(res.data.data.length)
          let num = Math.floor(res.data.data.length / 10);
          let yushu = res.data.data.length % 10;
          // console.log(num,yushu)
          setPageNmu(num);
          setPageYu(yushu);
        }
      })
      .catch((err) => {
        console.log("获取所有学生数据1111", err);
      });
    // console.log(11)
    // setDateList(data);
    // console.log(data)

    // console.log(num + "--------------", yushu);
  }, []);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const onSelectChange = (newSelectedRowKeys) => {
    console.log("selectedRowKeys changed: ", newSelectedRowKeys);
    setArrId(newSelectedRowKeys)
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  //
  const [currents, setCurrents] = useState(1);
  //单选框数据,表格下面的全选按钮
  const [RadioState, setRadioState] = useState(false);

  const changeRadio = () => {

  console.log("==============")
  let end = 10 * currents - 1;
  let start;
  if (currents > 1) {
    start = end - 9;
  } else {
    start = 0;
  }
  console.log(start, end);
//通过下标拿id
let arr = [];
let datas = [];
if (pageNmu >= currents) {
  for (let i = start; i <= end; i++) {
    arr.push(dataList[i].n_id);
  }
} else if (pageNmu < currents) {
  for (let i = start; i <= end; i++) {
    datas.push(i);
  }
  console.log("==============")
  console.log(datas);
  console.log(pageYU);
  let dataIndex = [];
  for (let i = 0; i < pageYU; i++) {
    dataIndex.push(datas[i]);
  }
  console.log(dataIndex);
  for (
    let i = dataIndex[0];
    i <= dataIndex[0] + dataIndex.length - 1;
    i++
  ) {
    arr.push(dataList[i].n_id);
  }
}

console.log(arr);
if (RadioState === false) {
  setRadioState(true);
  // setSelectedRowKeys([1, 17, 18]);
  onSelectChange([...arr]);
} else {
  setRadioState(false);
  setSelectedRowKeys([]);
  onSelectChange([]);
}

  };
  const getPage = (e) => {
    // console.log(dataList.length);
    setRadioState(false);
    setCurrents(e.current);
    console.log(e.current);
  };
  //批量操作
  const [czState, setCzState] = useState("");
  const plcz = (value) => {
    setCzState(value);
  };
  //确定批量操作
  const qd = () => {
    console.log(selectedRowKeys);
    let a=[];
    for (let i=0;i<=selectedRowKeys.length-1;i++){
      a.push(selectedRowKeys[i])
    }
    if (selectedRowKeys.length === 0) {
      console.log(0);

      messageApi.info("没有选择删除的数据!");
    } else {
      if (czState === "") {
        console.log(11);
        messageApi.info("没有选择相应的操作!");
      } else if (czState === "删除") {
        axios({
          url: "/noticeDel",
          method: "post",
          data: {
            idArr: ArrId,
          },
        })
          .then((res) => {
            console.log("获取所有学生数据", res);
    
            if (res.status === 200) {
             console.log("数据删除成功")
             messageApi.info("删除成功!");
            }
          })
          .catch((err) => {
            console.log("获取所有学生数据1111", err);
          });
      }
    }
  };
  //发布消息
  const onFinish=(values)=>{
    let myDate = new Date()
    let myYear = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
    let myMonth = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
    let myToday = myDate.getDate(); //获取当前日(1-31)
    myMonth = myMonth > 9 ? myMonth : '0' + myMonth
    myToday = myToday > 9 ? myToday : '0' + myToday
    let nowDate = myYear +"-"+  myMonth + "-"+ myToday
  console.log(nowDate)
    console.log("============")
    let arr={
      n_time:nowDate,
      n_title:values.title,
      n_user:"白泽",
      n_content:values.content,
    }//添加接口
    axios({
      url: "/addNotice",
      method: "post",
      data:arr,
    })
      .then((res) => {
        console.log("===============")
              console.log(res)
              axios({
                url: "/getNoticeData",
                method: "post",
              })
                .then((res) => {
                  console.log("获取所有学生数据", res);
          
                  if (res.status === 200) {
                    setDateList(res.data.data);
                    setdatas(res.data.data)
                    // console.log(res.data.data.length)
                    let num = Math.floor(res.data.data.length / 5);
                    let yushu = res.data.data.length % 5;
                    // console.log(num,yushu)
                    setPageNmu(num);
                    setPageYu(yushu);
                  }
                })
                .catch((err) => {
                  console.log("获取所有学生数据1111", err);
                });
              // console.log(11)
              // setDateList(data);
              // console.log(data)
          
      })
      .catch((err) => {
        console.log("获取所有学生数据1111", err);
      });
    messageApi.info("发布成功!");
    setissendModalOpen(false)
 console.log(values)
  }
  const addmsg = () => {
    console.log(111);
    setissendModalOpen(true)
    //  navigate("/HomePage/AddGg")
  };
  const closeM=()=>{
    setissendModalOpen(false)
  }
  // const hasSelected = selectedRowKeys.length > 0;
  return (
    <div 
      style={{
        width: "100%",
        display: "flex",
        justifyContent: "center",
        flexDirection: "column",
        alignItems: "center",
        height: "95%",
      }}
    >
      <div 
        style={{
          width: "97%",
          display: "flex",
          justifyContent: "flex-start",
          marginTop: "10px",
          zIndex: "999",
          backgroundColor: "white",
          //   border: "1px solid red",
          height: "8%",
        }}
      >
        <form
          style={{
            width: "100%",
            display: "flex",
            justifyContent: "flex-start",
          }}
        >
          <Input
            value={inputValue}
            onChange={(value) => {
              changeInput(value);
            }}
            placeholder="消息标题"
            style={{ width: "15%", marginRight: "1%", height: "33px" }}
          />
          <Select
            defaultValue="全部"
            style={{
              width: "15%",
              marginRight: "1%",
              textAlign: "left",
              height: "33px",
            }}
            onChange={swiperChange}
            options={[
              {
                value: "全部",
                label: "全部",
              },
              {
                value: "从有",
                label: "从有",
              },
              {
                value: "admin",
                label: "admin",
              },
              {
                value: "白泽",
                label: "白泽",
              }
            ]}
          />
          <Space direction="vertical"  style={{ marginRight: "1%" }}>
            <DatePicker onChange={onChange} placeholder="选择日期" />
          </Space>
          <Button
            type="primary"
            onClick={searchDate}
            style={{ width: "7%", marginRight: "1%", height: "33px" }}
          >
            查询
          </Button>
          <Button
            type="primary"
            onClick={getALLDate}
            style={{ width: "7%", marginRight: "1%", height: "33px",textAlign:"center",display:"flex",justifyContent:"center",alignItems:"center"}}
          >
            所有数据
          </Button>
          <Button
            type="primary"
            onClick={addmsg}
            style={{
              width: "7%",
              marginRight: "1%",
              backgroundColor: "#ffffff",
              color: "black",
              border: "1px solid #cccccc",
              height: "33px",
            }}
          >
            发布信息
          </Button>
        </form>
      </div>
      <div
        className="table-div "
        style={{
          width: "97%",
          height: "96%",
          overflowY: "scroll",
          // border:"1px solid red"
          //   overflow: "hidden",
        }}
      >
        <Table
          rowKey={(record) => record.n_id}
          pagination={{ defaultPageSize: 10 }}
          rowSelection={rowSelection}
          columns={columns}
          dataSource={dataList}
          onChange={(current) => {
            getPage(current);
          }}
        />
        <div
          className="btn"
          style={{ display: "flex", marginTop: "-40px", alignItems: "center" ,marginLeft:"112px" }}
        >
          <Radio
            checked={RadioState}
            onClick={changeRadio}
            style={{ marginLeft: "15px", borderRadius: "0px" }}
          >
            <span style={{marginLeft:"-30px"}}> 全选</span>
          </Radio>
          <Select
            defaultValue="批量操作"
            style={{
              // width: "10%",
              marginRight: "1%",
              textAlign: "left",
              height: "33px",
              marginLeft:"-20px"
            }}
            onChange={plcz}
            options={[
              {
                value: "删除",
                label: "删除",
              },
            ]}
          />
          <Button
            className="but"
            type="primary"
            onClick={qd}
            style={{
              width: "80px",
              height: "33px",
              textAlign: "center",
              backgroundColor: "white",
              color: "black",
              marginLeft:"10px",
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            确定
          </Button>
        </div>
      </div>
      {contextHolder}
      <Modal
        title="确认提示"
        okText="确认"
        cancelText="取消"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        style={{ marginTop: "10%", overflow: "hidden" }}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            flexDirection: "column",
          }}
        >
          <div
            style={{
              display: "flex",
              flexDirection: "row",
              justifyContent: "center",
              alignItems: "center",
              marginBottom: "20px",
            }}
          >
            <ExclamationCircleOutlined
              style={{ fontSize: "30px", color: "red", marginRight: "10px" }}
            />
            <span style={{ fontWeight: 800, fontSize: "20px" }}>系统提示</span>
          </div>
          <span>确定删除该条公告的消息吗？</span>
          <hr
            style={{
              width: "120%",
              border: "#e4e4e4 1px solid",
              marginTop: "20px",
              marginLeft: "-10%",
            }}
          ></hr>
        </div>
      </Modal>
      
      <Modal
      className="Announcement"
        title="查看详情"
        cancelText="取消"
        footer={""}
        open={isselectModalOpen}
        onOk={handleselectOk}
        onCancel={handleselectCancel}
        style={{ marginTop: "5%", overflow: "hidden"}}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            flexDirection: "column",
           
          }}
        > 

        <div style={{display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center"}}>
           <span style={{fontSize:"20px",color:"#666666"}}> {selectDate.n_title}</span>
           <span style={{fontSize:"18px",color:"#d5d5d5"}}> {selectDate.n_time}</span>
        </div>
        <div style={{width:"100%",border:"1px solid #e4e4e4"}}>
       
        </div>
          <div style={{marginTop:"20px",marginBottom:"20px",width:"100%",height:"150px"}}>
         {selectDate.n_content}
          </div>
        </div>
      </Modal>
      <Modal
      className="Announcement"
        title="发布信息"
        cancelText="取消"
        okText="发布"
        footer={""}
        open={issendModalOpen}
        onOk={handlesendOk}
        onCancel={handlesendCancel}
        style={{ marginTop: "5%", overflow: "hidden"}}
      >
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            flexDirection: "column",
           
          }}
        > 

      
        
        <Form
         onFinish={onFinish} 
        style={{marginTop:"20px",position:"relative"}}>
        <Form.Item
              label="title"
              name="title"
              rules={[
                {
                  required: true,
                  message: "请输入消息标题!",
                },
              ]}
            >
              <Input placeholder="请输入消息标题" />
            </Form.Item>
            <Form.Item label="content" name="content"    rules={[
                {
                  required: true,
                  message: "请输入消息内容!",
                },
              ]}>
              <TextArea rows={5} placeholder="请输入消息内容"  style={{width:"300px"}}/>
            </Form.Item>
            
            <Form.Item
              wrapperCol={{
                offset: 23,
                span: 16,
                
              }}
            >
              <Button
                type="primary"
                htmlType="submit"
                style={{ backgroundColor: "#1677ff",marginTop:"40px",marginBottom:"-100px" }}
              >
                发布
              </Button>
            </Form.Item>
            <div  type="" onClick={closeM} style={{position:"absolute",top:"82.5%",marginLeft:"75%",backgroundColor:"#1677ff",height:"32px",width:"60px",border:"0px",color:"white",borderRadius:"5px",textAlign:"center",lineHeight:"32px"}}>取消</div>
        </Form>
        </div>
      </Modal>
     
    </div>
  );
};
export default Announcement;
